package com.mylib.libcore.tools;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import androidx.annotation.MainThread;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.eventbus.ChangeMessage;
import com.mylib.libcore.utils.ScreenUtils;
import com.mylib.libcore.utils.UIUtils;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import static com.mylib.libcore.config.AppConfig.CSJ_JL_ONE_ID;
import static com.mylib.libcore.config.AppConfig.CSJ_OPEN_ID;

/**
 * @author Administrator
 * @date 2020/6/30-11:17
 * @description
 **/
public class CSJADTools {
    private static  final String TAG = "CSJADTools";
    public static TTAdNative mTTAdNative;
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 5000;
    public static TTRewardVideoAd mAd;
    public static TTRewardVideoAd getmAd() {
        return mAd;
    }
    public static void setmAd(TTRewardVideoAd mAd) {
        CSJADTools.mAd = mAd;
    }
    private static AdSlot adSlot;
    public static AdSlot getAdSlot(String rewardName,int reAwardNum,String keyType){
      return   adSlot = new AdSlot.Builder()
                .setCodeId(CSJ_JL_ONE_ID)
                .setSupportDeepLink(true)
                .setRewardName(rewardName) //奖励的名称
                .setRewardAmount(reAwardNum)  //奖励的数量
                //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
                .setExpressViewAcceptedSize(500,500)
                .setUserID(AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id")+"")//用户id,必传参数
                .setMediaExtra(""+keyType) //附加参数，可选
                .setOrientation(TTAdConstant.VERTICAL)  //设置期望视频播放的方向，为TTAdConstant.HORIZONTAL或TTAdConstant.VERTICAL
                .build();
    }

    //获取穿山甲广告
    public static void getCSJOpenAD(Activity activity, FrameLayout splashContainer){
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        try {
            int width = 1080;
            int height = 1920;
            try {
                width = ScreenUtils.getScreenWidth(activity);
                height = ScreenUtils.getScreenWidth(activity)-UIUtils.dp2px(80);
            } catch (Exception e) {
                e.printStackTrace();
            }

            mTTAdNative = TTAdManagerHolder.get().createAdNative(activity);
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(CSJ_OPEN_ID)
                    .setImageAcceptedSize(width, height)
                    .build();
            //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
            mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
                @Override
                @MainThread
                public void onError(int code, String message) {
                     UIUtils.goToMainActivity();
                }

                @Override
                @MainThread
                public void onTimeout() {  UIUtils.goToMainActivity(); }

                @Override
                @MainThread
                public void onSplashAdLoad(TTSplashAd ad) {
                    if (ad == null){
                         UIUtils.goToMainActivity();
                        return;
                    }

                    //获取SplashView
                    View view = ad.getSplashView();
                    if (view != null && splashContainer != null && !activity.isFinishing()) {
                         splashContainer.removeAllViews();
                        //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                        splashContainer.addView(view);
                    }else {
                         UIUtils.goToMainActivity();
                    }

                    //设置SplashView的交互监听器
                    ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                        @Override
                        public void onAdClicked(View view, int type) {
                            //ToastUtil.show("开屏广告点击");
                        }

                        @Override
                        public void onAdShow(View view, int type) {
                            // ToastUtil.show("开屏广告展示");
                        }

                        @Override
                        public void onAdSkip() {
                            // ToastUtil.show("开屏广告跳过");
                             UIUtils.goToMainActivity();

                        }

                        @Override
                        public void onAdTimeOver() {
                            // ToastUtil.show("开屏广告倒计时结束");
                             UIUtils.goToMainActivity();
                        }
                    });
                }
            }, AD_TIME_OUT);
        }catch (Exception e){
             UIUtils.goToMainActivity();
        }
    }

    /**
     * 广告监听
     * @param ad
     * @param rl_item
     */
    public static void bindAdListener(TTNativeExpressAd ad, RelativeLayout rl_item) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
            }

            @Override
            public void onAdShow(View view, int type) {
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                rl_item.removeAllViews();
                rl_item.addView(view);
            }
        });
    }

    /**
     * 穿山甲广告banner
     */
    public static void loadCSJAdMiddleBanner(Context context,RelativeLayout rl_ad,String showType, String ad_id, int width, int height){
        if(!UIUtils.isOpenAD()){
            rl_ad.setVisibility(View.GONE);
            return;
        }
        try{
            if(mTTAdNative == null){
                TTAdManagerHolder.init(context);
                mTTAdNative = TTAdManagerHolder.getTTAdNative(context);
                Log.d(TAG,"mTTAdNative");
            }
            final AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(ad_id) //广告位id
                    //  .setSupportDeepLink(true)
                    .setAdCount(3) //请求广告数量为1到3条
                   // .setImageAcceptedSize(width, height)
                    .setExpressViewAcceptedSize(width,height) //期望模板广告view的size,单位dp
                    .setNativeAdType(AdSlot.TYPE_BANNER) //请求原生广告时候，请务必调用该方法，设置参数为TYPE_BANNER或TYPE_INTERACTION_AD
                    .build();
            //加载广告
            //step5:请求广告，调用feed广告异步请求接口，加载到广告后，拿到广告素材自定义渲染
            //加载广告
            mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                @Override
                public void onError(int code, String message) {
                    Log.d(TAG,"error-"+message);
                    rl_ad.setVisibility(View.GONE);
                }

                @Override
                public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                    if (ads == null || ads.isEmpty()) return;
                    else ads.size();
                    Log.d(TAG,""+ads.size());
                    if(ads.size()>0){
                        CSJADTools.bindAdListener(ads.get(0) ,rl_ad);
                        ads.get(0).render();
                    }
                }
            });
        }catch (Exception e){
        }
    }
}
